<?php

namespace Theatre\View;

class HTML extends \Theatre\View {
	public $controller;


	/**
	 * Render response
	 *
	 * @param $controller The actual controller
	 */
	public function render($controller) {
		$this->controller = $controller;

		$template = $controller->template;
		$namespace = str_replace('Theatre\\', '', $controller->config['namespace']);

		if (empty($template)) {
			$template = $controller->config['docRoot'] . '/Theatre/View/Templates/' . $namespace . '/' . $controller->name . '/' . $controller->action . '.tpl';
		}
		else {
			$template = $controller->config['docRoot'] . '/Theatre/View/Templates/' . $controller->template . '.tpl';
		}

		$layout = $controller->config['docRoot'] . '/Theatre/View/Templates/layout.tpl';

		// render the template
		$contentForLayout = $this->_renderFile($template, $controller->viewVars);

		// now render the layout
		return $this->_renderFile($layout, array('contentForLayout' => $contentForLayout) + $controller->viewVars);
	}


	/**
	 * Render a specified file
	 *
	 * @param $filePath The fill path to the template
	 * @param $___dataForView The data present in the template
	 */
	private function _renderFile($filePath, $___dataForView) {
		if (!file_exists($filePath)) {
			throw new \Exception("Missing template {$filePath}");
		}

		extract($___dataForView, EXTR_SKIP);

		ob_start();
		include ($filePath);
		return ob_get_clean();
	}

	public function clean($text) {
		return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
	}

	public function url($uri) {
		return $this->controller->base . $uri;
	}
}
